<template>
  <div v-loading="loading">
    <SectionTitle title="当前客户信息" style="margin-bottom: 10px;" />
    <el-form
      ref="customerForm"
      :rules="rules"
      :model="formData"
      :label-position="showMobilePage?'left':'right'"
      :class="{'mobile-el-form': showMobilePage}"
      class="lineHeight32 customer-form"
      label-width="110px">
      <el-row type="flex" class="response-el-row">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="客户名称:" class="client-item" prop="customerId">
            <div class="flex-center">
              <ToolTip v-if="isDetail" :content="detailData.customerName" is-can-click @handelClick="handelClick" />
              <selectWithoutHttp
                v-else
                v-model="customerId"
                :remote-method="getClientNameMethods"
                :list-data="clientNameOption"
                :default-list="defaultClientOption"
                :delay="200"
                :placement="'right'"
                label-name="value"
                extend-class="order-client-select"
                key-name="id"
                filterable
                add-new
                add-new-str="添加新客户"
                remote
                placeholder="搜索匹配"
                clearable
                @clear="onClear"
                @addNewClick="addNewClick"
                @change="onClientChange" />
              <SearchContract :class="!customerId && 'disabled-sc'" :opp-company-id="customerId" :opp-company="formData.clientName" :opp-company-type="3" />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="客户等级:">
            <span v-if="!formData.levelColor">{{ formData.clientGrade || '--' }}</span>
            <div v-else :style="{color: formData.levelColor, background: changeColorAlphaVal(formData.levelColor, 0.14)}" class="text-bg">{{ formData.clientGrade || '--' }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="客户行业:">
            <span>{{ formData.clientBusiness || '--' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="所属集团:">
            <ToolTip :content="formData.group | formatTag" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="备注:">
            <ToolTip :content="formData.remark" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="客户类型:">
            <span v-if="formData.clientType || formData.clientType === 0">{{ formData.clientType | clientStatusFilter }}</span>
            <span v-else>{{ formData.clientType || '--' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="欠款额度(元):">
            <div class="flex-center">
              <el-tooltip v-if="formData.oweData && (formData.oweData.availableAmount || formData.oweData.availableAmount === 0)" :open-delay="800" placement="top">
                <div slot="content" style="max-width:200px;" >
                  {{ (formData.oweData.availableAmount) | moneyFilter(true, '', true) }} / {{ (formData.oweData.totalAmount) | moneyFilter(true, '', true) }}
                </div>
                <div><span style="color: red">{{ (formData.oweData.availableAmount) | bigDataFilter(true, '', true, 2) }}</span>/<span>{{ (formData.oweData.totalAmount) | bigDataFilter(true, '', true, 2) }}</span></div>
              </el-tooltip>
              <span v-else>--</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="标签:">
            <TagSelect v-model="formData.tag" mode="detail" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="所属部门:">
            <ToolTip :content="formData.department | formatTag" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="客户状态:">
            <div v-if="!formData.statusColor">{{ formData.clientStatusStr || '--' }}</div>
            <div v-else :style="{color: formData.statusColor, background: changeColorAlphaVal(formData.statusColor, 0.14)}" class="text-bg">{{ formData.clientStatusStr || '--' }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="欠款账期:">
            <span>{{ formData.accountPeriod || '--' }} 天</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="客户来源:">
            <span>{{ formData.clientSource || '--' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="销售:">
            <ToolTip :content="formData.sale" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import SearchContract from '@/components/Common/SearchContract';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import TagSelect from '@/components/Common/tagSelect';
import { getClientName } from '@/api/select';
import { getClientInfo } from '@/api/customer';
import { clientStatusFilter } from '@/filters/status';
import { formatTag } from '@/filters/dept';
import { moneyFilter, bigDataFilter } from '@/filters/number';
import { changeColorAlphaVal } from '@/utils/tools';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';

export default {
  components: {
    SectionTitle,
    SearchContract,
    selectWithoutHttp,
    TagSelect
  },
  filters: {
    formatTag,
    moneyFilter, bigDataFilter,
    clientStatusFilter
  },
  props: {
    clientId: {
      type: Number,
      default: null
    },
    defaultCustomerName: {
      type: String,
      default: ''
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    detailData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      loading: false,
      clientNameOption: [],
      customerId: null,
      formData: {}
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    rules() {
      return {
        'customerId': [{ required: true, message: '请选择当前客户', trigger: 'blur' }]
      };
    },
    defaultClientOption() {
      return [{ id: this.clientId, value: this.defaultCustomerName }];
    }
  },
  watch: {
    clientId: {
      handler(val) {
        if (val) {
          this.customerId = val;
          this.onClientChange(val);
        }
      }
    },
    detailData: {
      handler(val) {
        if (val) {
          const { customerLevel, customerName, customerStatusStr, customerSource, customerType, customerId } = val;
          this.formData = {
            ...val,
            clientGrade: customerLevel,
            clientStatusStr: customerStatusStr,
            clientSource: customerSource,
            clientType: customerType,
            clientName: customerName
          };
          this.customerId = customerId;
        }
      },
      immediate: true
    }
  },
  created() {
    this.getClientNameMethods(null, true);
  },
  methods: {
    changeColorAlphaVal,
    hasRouteAuth,
    getClientInfo(id) {
      return new Promise((resolve, reject) => {
        getClientInfo(id).then(res => {
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    onClientChange(id) {
      if (id) {
        this.loading = true;
        this.getClientInfo(id).then(res => {
          if (res.code === 200) {
            this.formData = res.data;
            this.formData.customerId = id;
            this.$emit('setClientInfo', res.data);
          }
          this.loading = false;
        }).catch(err => {
          console.error(err.message);
          this.loading = false;
        });
        this.$refs.customerForm.clearValidate('customerId');
      } else {
        this.formData.customerId = null;
        this.validateForm();
      }
    },
    onClear() {
      this.formData = {};
      this.$refs['customerForm'].validate();
    },
    // 获取客户列表
    getClientNameMethods(name = '', notShowNoAuthTip = false) {
      const param = {
        clientName: name,
        isGetMengliClient: false
      };
      getClientName(param, 1, notShowNoAuthTip).then(res => {
        this.clientNameOption = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs['customerForm'].validate().then(() => {
          resolve();
        }).catch(() => {
          reject();
        });
      });
    },
    getFormData() {
      const params = _.cloneDeep(this.formData);
      params.customerId = this.customerId;
      return params;
    },
    addNewClick() {
      if (!this.hasRouteAuth('crm:customer:add')) {
        this.$message.error('您暂无新增客户权限');
        return;
      }
      const routeUrl = this.$router.resolve({ name: 'createCustomer' });
      window.open(routeUrl.href, '_blank');
    },
    handelClick() {
      const routeUrl = this.$router.resolve({
        name: 'detailCustomer',
        params: {
          customerId: this.detailData.customerId
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.customer-form {
  margin-bottom: 14px;
  &::v-deep {
    .el-form-item {
      overflow: hidden;
      margin-bottom: 0;
      .el-form-item__label {
        color: #999;
      }
      &.client-item {
        overflow: unset;
      }
    }
    .el-form-item__content {
      border-right: 1px solid #EBEEFD !important;
    }
    &:nth-child(3n) {
      .el-form-item__content {
        border-right: none !important;
      }
    }
    &:last-child {
      .el-form-item__content {
        border-right: none;
      }
    }
  }
  .disabled-sc {
    ::v-deep .button-text {
      cursor: not-allowed;
      color: #999;
      pointer-events: none;
    }
  }
  .text-bg {
    padding: 0 10px;
    border-radius: 999px;
    display: inline-block;
    height: 20px;
    line-height: 20px;
  }
}
</style>
